# -*- coding: utf-8 -*-
from time import sleep
import serial

try:
    ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
except:
    print('usb error,请检查USB插线，并重启程序')
    exit(0)

def get_gps_data(waittime=0.01):
    data = 'Error'
    cnt = 0
    try:
        ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
        ser.reset_input_buffer()
        while True:
            data = ser.readline()
            data = data.decode('GBK')
            if 'GGA' in data:
                break
            if waittime:
                sleep(waittime)
            cnt += 1
            if cnt > 50:
                data = 'Error'
                print('gps error，请检查GPS设备，并重启程序')
                break
    except:
        data = 'Error'
        print('usb error,请检查USB插线，并重启程序')

    return data


def get_gps_data_pro(waittime=0.01, speed_thresh=5):
    data = 'Error'
    speed = 0
    cnt = 0
    cnt_lowspeed = 0
    try:
        ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
        ser.reset_input_buffer()
        while True:
            data = ser.readline()
            data = data.decode('GBK')
            if 'GNVTG' in data:
                _data = data.split(',')
                if len(_data) >= 10:
                    speed = float(_data[7])
                continue
            if 'GGA' in data:
                gga = int(data.split(',')[6])
                if not gga in [4, 5]:
                    continue
                if speed > speed_thresh:  # 5km/hour
                    break
                else:
                    cnt_lowspeed += 1
            if waittime:
                sleep(waittime)
            if cnt_lowspeed >= 10:
                print('low speed')
                cnt = 0
                cnt_lowspeed = 0
                continue
            cnt += 1
            if cnt >= 100:
                print('usb error,请检查USB插线，并重启程序')
                data = 'Error'
                break
    except:
        print('usb error2,请检查USB插线，并重启程序')
        data = 'Error'

    return data, str(speed)


# if __name__ == '__main__':
#     pygame.init()
#     size = width, height = 320, 240  # 设置窗口大小
#     screen = pygame.display.set_mode(size)  # 显示窗口
#     while True:  # 死循环确保窗口一直显示
#         print(get_gps_data())
        # for event in pygame.event.get():  # 遍历所有事件
        #     if event.type == pygame.QUIT:  # 如果单击关闭窗口，则退出
        #         sys.exit()
        #     if event.type == pygame.KEYDOWN:
        #         if event.key == pygame.K_SPACE:
        #             print('get_gps_data')
        #             data = get_gps_data(ser)
